package com.icss.ah.login.action;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.icss.ah.base.action.BaseAction;
import com.icss.ah.base.bean.Json;
import com.icss.ah.base.util.MD5Util;
import com.icss.ah.login.bean.UserInfoBean;

/**
 * 登录控制
 * @author csadchen
 * @date 2016-09-06
 */
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction{
	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");

	private String userCode;
	private String password;
	private UserInfoBean userInfo;
	
	private String emailCode;
	/**
	 * 平台入口，判断是否已经登录
	 * @return
	 */
	public String login(){
		String forwardPage = "login";
		try {
			//从session获取登录人员账号
			String userCode = getUserCodeFromSession();
			if(loginService.checkUserShop(userCode)){//拥有店铺
				getRequest().getSession().setAttribute("userShopExist", "1");
			}else{
				getRequest().getSession().setAttribute("userShopExist", "0");
			}
			if(!userCode.equals("")){
				//已经登录，进入首页
				forwardPage = "mainIndex";
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("Login|异常：",e);
		}
		return forwardPage;
	}
	/**
	 * 获取用户信息
	 */
	public void getUserInfo(){
		userInfo = new UserInfoBean();
		jsonText = new Json();
		try {
			//根据登录人员账号获取人员信息
			String userCode = getUserCodeFromSession();
			userInfo = loginService.getUserInfo(userCode);
			userInfo.setUserCode(userCode);
			//返回人员信息
			jsonText.setSuccess(true);
			jsonText.setObj(userInfo);
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|获取用户信息异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	/**
	 * 验证账号密码登录
	 */
	public void checkLoginInfo(){
		jsonText = new Json();
		try {
			//获取登录账号密码并与输入密码进行比对
			password = password == null ? "" : password;
			String queryPass = loginService.getUserPassword(userCode);
			if(queryPass.equals("")){
				//账号不存在，未获取到密码
				jsonText.setSuccess(false);
				jsonText.setMsg("no_user");
			} else if(MD5Util.toMD5(password).equals(queryPass)){
				//密码比对正确，允许登录
				getRequest().getSession().setAttribute("userCode", userCode);
				getRequest().getSession().setAttribute("password", password);
				jsonText.setSuccess(true);
				infolog.info("Login|"+userCode+"登录系统");
			} else {
				//密码比对错误
				jsonText.setSuccess(false);
				jsonText.setMsg("error_pass");
				infolog.info("Login|"+userCode+"密码错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|登录异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	/**
	 * 验证用户帐号与邮箱帐号，重置密码
	 */
	public void checkEmailCode(){
		jsonText = new Json();
		try {
			//获取登录账号与邮箱帐号并与输入邮箱帐号进行比对
			emailCode = emailCode == null ? "" : emailCode;
			Map emailMap = new HashMap();
			emailMap = loginService.getEmailCode(userCode);
			emailMap = emailMap == null? new HashMap():emailMap;
			Object queryEmailr = emailMap.get("EMAIL");
			String queryEmail = isEmpty(queryEmailr);	//邮箱帐号
			Object authenticationr = emailMap.get("EMAIL_AUTHENTICATION");
			String authentication =  isEmpty(authenticationr);//邮箱是否认证
			if(queryEmail.equals("")){
				//账号不存在，未获取到邮箱帐号
				jsonText.setSuccess(false);
				jsonText.setMsg("no_user");
			} else if(emailCode.equals(queryEmail)){
				//帐号邮箱比对正确，判断邮箱是否认证，若已认证，则允许重置密码
				if(authentication.equals("1")){//邮箱已认证
					getRequest().getSession().setAttribute("userCode", userCode);
					getRequest().getSession().setAttribute("emailCode", emailCode);
					jsonText.setSuccess(true);
					jsonText.setMsg("");
				}else{//邮箱未认证
					getRequest().getSession().setAttribute("userCode", userCode);
					getRequest().getSession().setAttribute("emailCode", emailCode);
					jsonText.setSuccess(false);
					jsonText.setMsg("no_access");
				}
				infolog.info("Login|"+userCode+"帐号邮箱比对，是否重置密码");
			} else {
				//邮箱比对错误
				jsonText.setSuccess(false);
				jsonText.setMsg("error_pass");
				infolog.info("Login|"+userCode+"邮箱帐号错误");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|登录异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	/**
	 * 判断obj类型，并做处理
	 * @param obj
	 * @return
	 */
	 public String isEmpty(Object obj){  
		 String result = "";
	        if (obj == null)  
	        {  
	            return "";  
	        }  
	        if (obj instanceof String)  
	        {  
	            return obj.toString();  
	        }   
	        if (obj instanceof Integer){
	        	 return obj.toString();  
	        }   
	        return result;
	    }  
	/**
	 * 登出系统
	 * @return
	 */
	public String login_out(){
		String userCode = getUserCodeFromSession();
		removeUserInfo(userCode);
		infolog.info("Login|"+userCode+"登出系统");
		return "login";
	}
	
	/**
	 * 注册部分
	 * @return
	 */
	/**
	 * 判断用户名是否存在
	 */
	public void checkUserCodeExist(){
		jsonText = new Json();
		try {
			//根据输入账号判断此账号是否已存在
			boolean result = loginService.checkUserCodeExist(userCode);
			jsonText.setSuccess(result);
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|判断用户名是否存在异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	/**
	 * 注册
	 */
	public void doRegister(){
		jsonText = new Json();
		try {
			//允许注册
			String realName = getRequest().getParameter("realName");
			realName = realName == null ? "" : realName;
			
			HashMap info = new HashMap();
			info.put("userCode", userCode);
			info.put("password", MD5Util.toMD5(password));
			info.put("realName", realName);
			info.put("emailCode", emailCode);
			//保存注册信息
			boolean result = loginService.doRegister(info);
			if(result){
				getRequest().getSession().setAttribute("userCode", userCode);
				getRequest().getSession().setAttribute("password", password);
			}
			jsonText.setSuccess(result);
		} catch (Exception e) {
			e.printStackTrace();
			jsonText.setSuccess(false);
			jsonText.setMsg(e.getMessage());
			errlog.error("Login|注册异常：",e);
		}
		str2Resp(JSONObject.fromObject(jsonText).toString());
	}
	
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setUserInfo(UserInfoBean userInfo) {
		this.userInfo = userInfo;
	}
	public String getEmailCode() {
		return emailCode;
	}
	public void setEmailCode(String emailCode) {
		this.emailCode = emailCode;
	}
}
